import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// import legacyPlugin from "@vitejs/plugin-legacy";
import { Plugin as ImportToCDN } from "vite-plugin-cdn-import";
import compression from "vite-plugin-compression";
import babel from "vite-plugin-babel";
import modules from "./cdn/modules.json";
import { convert } from "./cdn/index";

// https://vitejs.dev/config/
export default defineConfig({
  base: "./",
  build: {
    outDir: "html",
    // sourcemap: true,
    rollupOptions: {
      external: [
        "react",
        "react-dom",
        "lodash",
        // "antd",
        // "react-redux",
        // "react-router-dom",
      ],
    },
  },
  optimizeDeps: {
    include: ["react", "react-dom", "lodash"],
  },
  plugins: [
    react(),
    babel({
      libraryName: "antd",
      style: false, // or 'css'
    }),
    compression({
      verbose: true, // 是否在控制台输出压缩信息
      disable: false, // 是否禁用压缩
      threshold: 10240, // 设置压缩的最小文件大小（字节），默认 10240（10KB）
      algorithm: "gzip", // 压缩算法，默认 'gzip'
      ext: ".gz", // 压缩文件的扩展名，默认 '.gz'
    }),
    ImportToCDN({
      resolve: {
        alias: {
          lodash:
            "https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/lodash.js/4.17.21/lodash.min.js",
          // antd: "https://cdn.bootcdn.net/ajax/libs/antd/5.23.3/antd.min.js",
        },
      },
      modules,
    }),
    // legacyPlugin({
    //   targets: ["ie >= 11"],
    //   additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
    //   renderLegacyChunks: true,
    // }),
    {
      name: "build-complete",
      closeBundle() {
        const file = path.resolve("./html/index.html");
        console.log("index file: ", file);
        convert(file);
        console.log("✅ build finished!");
      },
    },
  ],
  // base: "https://laremehpe.gitee.io/",
  server: {
    proxy: {
      "/api": {
        // target: "https://laremehpe.eu.org:9090",
        target: "http://localhost:8080",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
    host: true,
    port: 5173,
  },
});
